package com.youngking.guns.modular.weixin;




import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.youngking.guns.modular.system.model.Wxuserinfo;
import com.youngking.guns.modular.wxuserinfo.service.IWxuserinfoService;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
 * 获取code后，请求以下链接获取access_token：
 */
@Controller
@RequestMapping("/callBackController")
public class CallBackController {
    @Autowired
    private IWxuserinfoService  wxuserinfoService;
    @RequestMapping("/callBack")
    public String callBack(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException, WeixinException {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        Weixin weixin=new Weixin();
            try{
                String openid = weixin.sns().getOpenId(code);
                EntityWrapper ew = new EntityWrapper();
                ew.setEntity(new Wxuserinfo());
                ew.where("openid = {0}",openid);
                Wxuserinfo wxuserinfo = wxuserinfoService.selectOne(ew);
                if(wxuserinfo!=null){
                    return "redirect:http://www.ynyxgcxx.com/"+state+"?wxuserinfoid="+wxuserinfo.getId();
                }else {
                    return "redirect:http://www.ynyxgcxx.com/error";
                }
            }catch (Exception E){
                return E.getMessage();
            }
    }
}
